import request from "@/axios/request";
const { ElMessage } = require("element-plus");

export default {
  name: "TenantApplication",
  data() {
    return {
      loading: true,
      // 租户信息
      tenantId: "",
      username: "", // 新增：存储用户名
      // 申请数据
      total: 0,
      allData: [], // 接口返回的所有申请数据
      filteredData: [], // 筛选后的数据
      // 状态筛选开关（修复：变量名统一）
      pending: true,
      approved: true,
      rejected: true,
      // 房源信息映射
      houseMap: new Map() // 格式: Map(houseId => { title, address, ... })
    };
  },
  watch: {
    pending: { handler() { this.filterData(); } },
    approved: { handler() { this.filterData(); } },
    rejected: { handler() { this.filterData(); } }
  },
  created() {
    this.loading = true;
    // 获取租户ID和用户名
    const userInfo = JSON.parse(window.sessionStorage.getItem('userInfo') || '{}');
    this.tenantId = userInfo.tenantId || '';
    this.username = userInfo.username || '用户'; // 新增：从session获取用户名
    // 修复：页面加载时主动加载数据
    this.initData();
  },
  methods: {
    // 初始化数据
    async initData() {
      // 先加载申请记录，再加载房源信息
      await this.loadApplications();
      await this.loadHouseMap();
      this.loading = false;
    },

    async loadApplications() {
      try {
        const res = await request.get(`/rental/tenant/${this.tenantId}`);
        if (res.code === 200) {
          this.allData = res.data || [];
          this.total = this.allData.length;
          // 格式化申请时间
          this.allData.forEach(item => {
            item.formattedTime = this.formatTime(item.applicationTime);
          });
          // 空数据提示
          if (this.total === 0) {
            ElMessage.info("当前没有申请记录");
          } else {
            ElMessage.success(`加载成功，共${this.total}条申请`);
          }
          this.filterData(); // 筛选数据
        } else {
          ElMessage.error(res.msg || "加载申请失败");
          this.allData = [];
          this.total = 0;
        }
      } catch (err) {
        console.error("加载申请出错：", err);
        ElMessage.error("网络错误，请稍后重试");
        this.allData = [];
        this.total = 0;
      }
    },

    //申请的房源信息
    async loadHouseMap() {
      try {
        // 提取所有申请记录中的houseId
        const houseIds = [...new Set(this.allData.map(item => item.houseId).filter(Boolean))];
        if (houseIds.length === 0) {
          console.log("没有需要加载的房源ID");
          return;
        }

        // 查询房源信息
        for (const houseId of houseIds) {
          try {
            const res = await request.get(`/house/${houseId}`);
            if (res.code === 200 && res.data) {
              this.houseMap.set(houseId, res.data);
            } else {
              console.warn(`房源ID: ${houseId} 查询失败，原因：${res.msg || '未知错误'}`);
            }
          } catch (err) {
            console.error(`加载房源ID: ${houseId} 时出错:`, err);
          }
        }

        console.log(`共加载 ${this.houseMap.size}/${houseIds.length} 个房源信息`);
      } catch (err) {
        ElMessage.warning("房源信息加载失败，部分详情可能无法显示");
      }
    },

    
     // 筛选申请列表
    filterData() {
      this.filteredData = this.allData.filter(item => {
        if (item.status === "pending" && this.pending) return true;
        if (item.status === "approved" && this.approved) return true;
        if (item.status === "rejected" && this.rejected) return true;
        return false;
      });
    },

    //时间显示
    formatTime(isoTime) {
      if (!isoTime) return "-";
      const date = new Date(isoTime);
      // 手动格式化避免浏览器差异
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hour = String(date.getHours()).padStart(2, '0');
      const minute = String(date.getMinutes()).padStart(2, '0');
      const second = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
    },

    
    //申请类型
  
    getTypeLabel(type) {
      const typeMap = {
        "in": "入住申请",
        "out": "退房申请",
      };
      return typeMap[type] || "未知类型";
    },

    
    //退出登录

    SignOut() {
      sessionStorage.clear();
      ElMessage.success("已退出登录");
      this.$router.replace("/Login");
    },

    
     //状态标签样式
  
    getStatusTagType(status) {
      switch (status) {
        case "pending": return "warning";
        case "approved": return "success";
        case "rejected": return "danger";
        default: return "info";
      }
    },

    
     //状态文本
     
    getStatusLabel(status) {
      switch (status) {
        case "pending": return "待审核";
        case "approved": return "已通过";
        case "rejected": return "已拒绝";
        default: return "未知状态";
      }
    },

  
     //加快审批（无功能，起到一个造型上的作用）
    async handleSpeedUp(row) {
      try {
        ElMessage.warning("已加速审批");
      } catch (err) { 
        console.error("加快审批出错：", err);
        ElMessage.error("操作失败，请稍后重试");
      }
    },

    
     //删除beijujuede申请
     
    async handleDelete(row) {
      if (row.status !== "rejected") {
        ElMessage.warning("仅已拒绝的申请可删除");
        return;
      }
      try {
        const res = await request.delete(`/rental/delete/${row.applicationId}`);
        if (res.code === 200) {
          ElMessage.success("申请已删除");
          this.loadApplications(); // 重新加载
        } else {
          ElMessage.error(res.msg || "删除失败");
        }
      } catch (err) {
        console.error("删除申请出错：", err);
        ElMessage.error("网络错误");
      }
    },

    
     //退房申请
    async handleCheckOut(row) {
      // 校验：仅已通过的入住申请可提交退房
      if (row.status !== "approved" || row.type !== "in") {
        ElMessage.warning("仅已通过的入住申请可提交退房");
        return;
      }

      try {
        // 申请数据
        const requestData = {
          tenantId: this.tenantId, 
          houseId: row.houseId,    
          type: "out"              
        };
        const res = await request.post("/rental/apply", requestData);
        if (res.code === 200) {
          ElMessage.success("退房申请已提交");
          this.loadApplications(); // 重新加载申请列表
        } 
        else if (res.code === 404) {
          ElMessage.warning(res.msg || "未找到对应的租房申请，无法提交退房");
        } else {
          ElMessage.error(res.msg || "申请失败，请稍后重试");
        }

      } catch (err) {
        ElMessage.error("网络错误");
      }
    }
  }
};